#!/usr/bin/env bash
if [ $# == 0 ];then
  echo "You must enter a file like abc.txt"
  exit 1
fi

FileName=$1
DownloadUrlPrefix="https://gitee.com/bsos-top/open/raw/master/"

readonly color_normal="\033[m"
readonly color_red="\033[31m"
readonly color_green="\033[32m"
readonly color_yellow="\033[33m"
readonly color_blue="\033[34m"
readonly color_purple="\033[35m"
readonly color_cyan="\033[36m"
readonly color_white="\033[37m"

log() {
  case $1 in
  start)
    echo -e "[${color_green}Start${color_normal}] $2"
    ;;
  info)
    echo -e "[${color_purple} Info${color_normal}] $2"
    ;;
  warn)
    echo -e "[${color_yellow} Warn${color_normal}] $2"
    ;;
  error)
    echo -e "[${color_red}Error${color_normal}] $2"
    ;;
  esac
}

FileNameOut=$FileName

if [ "$FileName" == "common.sh" ];then
  if [ -f "common.sh" ];then
    FileNameOut=${FileName%%.*}
  fi
fi

log start $FileName
if [ -f "/usr/bin/wget" ];then
  wget -qN $DownloadUrlPrefix$FileName -O $FileNameOut
else
  curl -sfL $DownloadUrlPrefix$FileName -o $FileNameOut
fi

if [ "${FileNameOut##*.}" == "sh" -o "${FileNameOut##*.}" == "${FileNameOut}" ];then
  chmod u+x $FileNameOut
fi

if [ "$FileNameOut" == "$FileName" ];then
  log info $FileName Done
else
  log info "$FileName write to ${color_green}$FileNameOut${color_normal} Done"
fi
exit 0

